package com.myapp.util.mail;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class MailBuilder {

	private static final String TEMPLATE_FILE="WEB-INF/config/mail.ftl";
	
	private static final Logger logger = LoggerFactory.getLogger(MailBuilder.class);
	
    private JavaMailSender sender;  
    
    private Configuration  configurer = null;
    
    private Template  template = null;
  
    public void setConfiguration(Configuration configurer) {  
        this.configurer = configurer;  
    }  
    
    public void setSender(JavaMailSender sender) {
		this.sender = sender;
	}
	
	public void send(MailInfo info)
	{
		try {

	    	template = configurer.getTemplate(TEMPLATE_FILE);
			Map<String,String> valueMap = new HashMap<String,String>();
			StringWriter writer = new StringWriter();
			template.process(valueMap, writer);
			
			MimeMessage msg = sender.createMimeMessage();  
	        //false表示非marltipart,UTF-8为字符编码  
			MimeMessageHelper helper = null;
			
			helper = new MimeMessageHelper(msg, false, "UTF-8");  
			
	        helper.setSubject(info.getSubject());  
	        helper.setFrom(info.getFromAddress());  
	        if(info.getToAddress()== null)
	        {
	            helper.setTo(info.getToAddress()); 
	        }else
	        {
	            helper.setTo(info.getToAddresses()); 
	        }
	        helper.setText(writer.getBuffer().toString(), true);// 设置为true表示发送的是HTML  
	        sender.send(msg);
		} catch (IOException e) {
			logger.error("get mail template file unsucessfuly.", e);
		} catch (TemplateException e) {
			logger.error("get mail template file unsucessfuly.", e);
		}catch (MessagingException e) {
			e.printStackTrace();
		}		  
	}
}
